package com.sgcc.pms.api.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sgcc.pms.api.domain.Monitor;

import com.sgcc.pms.api.domain.MxpmsSearchEquipment;
import com.sgcc.pms.api.repository.MonitorRepository;
import com.sgcc.pms.api.web.rest.util.HeaderUtil;
import com.sgcc.pms.api.web.rest.util.PaginationUtil;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import io.swagger.annotations.ApiParam;
import io.github.jhipster.web.util.ResponseUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import java.text.ParseException;
import java.util.*;


/**
 * REST controller for managing Monitor.
 */
@RestController
@RequestMapping("/api")
public class MonitorResource {

    private static final CloseableHttpClient httpClient;

    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    private final Logger log = LoggerFactory.getLogger(MonitorResource.class);

    private static final String ENTITY_NAME = "monitor";

    private final MonitorRepository monitorRepository;

    public MonitorResource(MonitorRepository monitorRepository) {
        this.monitorRepository = monitorRepository;
    }

    /**
     * POST  /monitors : Create a new monitor.
     *
     * @param monitor the monitor to create
     * @return the ResponseEntity with status 201 (Created) and with body the new monitor, or with status 400 (Bad Request) if the monitor has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/monitors")
    @Timed
    public ResponseEntity<Monitor> createMonitor(@RequestBody Monitor monitor) throws URISyntaxException {
        log.debug("REST request to save Monitor : {}", monitor);
        if (monitor.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new monitor cannot already have an ID")).body(null);
        }
        Monitor result = monitorRepository.save(monitor);
        return ResponseEntity.created(new URI("/api/monitors/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /monitors : Updates an existing monitor.
     *
     * @param monitor the monitor to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated monitor,
     * or with status 400 (Bad Request) if the monitor is not valid,
     * or with status 500 (Internal Server Error) if the monitor couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/monitors")
    @Timed
    public ResponseEntity<Monitor> updateMonitor(@RequestBody Monitor monitor) throws URISyntaxException {
        log.debug("REST request to update Monitor : {}", monitor);
        if (monitor.getId() == null) {
            return createMonitor(monitor);
        }
        Monitor result = monitorRepository.save(monitor);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, monitor.getId().toString()))
            .body(result);
    }

    /**
     * GET  /monitors : get all the monitors.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of monitors in body
     */
    @GetMapping("/monitors")
    @Timed
    public ResponseEntity<List<Monitor>> getAllMonitors(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of Monitors");
        Page<Monitor> page = monitorRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/monitors");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /monitors/:id : get the "id" monitor.
     *
     * @param id the id of the monitor to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the monitor, or with status 404 (Not Found)
     */
    @GetMapping("/monitors/{id}")
    @Timed
    public ResponseEntity<Monitor> getMonitor(@PathVariable Long id) {
        log.debug("REST request to get Monitor : {}", id);
        Monitor monitor = monitorRepository.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(monitor));
    }

    /**
     * DELETE  /monitors/:id : delete the "id" monitor.
     *
     * @param id the id of the monitor to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/monitors/{id}")
    @Timed
    public ResponseEntity<Void> deleteMonitor(@PathVariable Long id) {
        log.debug("REST request to delete Monitor : {}", id);
        monitorRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * 搜索索引
     * @param params
     * @return
     */
    @PostMapping("/monV3/searchIndex")
    @Timed
    public String searchIndexV3(String params,@RequestBody String body) throws JsonParseException,IOException {
        // http://www.baeldung.com/httpclient-post-http-request
        // https://my.oschina.net/u/1270482/blog/212389
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");

        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");

        System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "debug");

        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");
        String result = null;
        List<MxpmsSearchEquipment> resultList = new ArrayList<MxpmsSearchEquipment>(); // 结果id集合
        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(body);

        String index = "filebeat-2017.12.05";
        String testStatusurl = "http://127.0.0.1:9200/";
        HttpPost request = new HttpPost(testStatusurl);
        CloseableHttpResponse response = httpClient.execute(request);
        int statusCode = 0;
        try {
            statusCode = response.getStatusLine().getStatusCode();
            if(HttpStatus.OK.value() == statusCode){//如果服务器返回成功
                String url = "http://127.0.0.1:9200/" + index + "/_search";
                JSONObject json = new JSONObject();
                actualObj = mapper.readTree(body);
                String str = "{\"query\": {\"match_phrase\" : {\"message\" : \"获取\"}}}";
                StringEntity stringEntity = new StringEntity(body, "UTF-8");
                stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                log.info("str="+str+"\n body="+body);
                request = new HttpPost(url);
                request.setEntity(stringEntity);
                response = httpClient.execute(request);
                try {
                    statusCode = response.getStatusLine().getStatusCode();
                    if(HttpStatus.OK.value() == statusCode){
                        HttpEntity entity = response.getEntity();
                        if (entity != null){
                            result = EntityUtils.toString(entity, "utf-8");
                            log.info("result="+result);
                        }
                        EntityUtils.consume(entity);
                    }else {
                        result = "获取数据失败:"+statusCode;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    response.close();
                }
            }else {
                result = "http://127.0.0.1:9200/服务器未开启:"+statusCode;
            }
            }catch (Exception e){
                e.printStackTrace();
        }finally {
            response.close();
        }
        log.info("result="+result);
        return result;
    }

    /**
     * 搜索索引
     * @param params
     * @return
     */
    @PostMapping("/monV4/searchIndex")
    @Timed
    public String searchIndexV4(@RequestParam Map<String, Object> param,@RequestBody String body) throws JsonParseException,IOException {

        https://www.jianshu.com/p/ed44e89a6f79

        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");

        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");

        System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "debug");

        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");
        String result = null;
        List<MxpmsSearchEquipment> resultList = new ArrayList<MxpmsSearchEquipment>(); // 结果id集合
        log.info("params="+"Request successful. Post param : Map - " + param);
//        return "Request successful. Post param : Map - " + param;

        String index = "filebeat-2017.12.12";
        String url = "http://127.0.0.1:9200/" + index + "/_search";
        JSONObject json = new JSONObject();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(body);
        String str = "{\"query\": {\"match_phrase\" : {\"message\" : \"DetailBizc:482 - 执行数据查询\"}}}";
        StringEntity stringEntity = new StringEntity(body, "UTF-8");
        stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        log.info("str="+str+"\n body="+body);
        HttpPost request = new HttpPost(url);
        request.setEntity(stringEntity);
        CloseableHttpResponse response = httpClient.execute(request);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if(HttpStatus.OK.value() == statusCode){
                HttpEntity entity = response.getEntity();
                if (entity != null){
                    result = EntityUtils.toString(entity, "utf-8");
                    log.info("result="+result);
                }
                EntityUtils.consume(entity);
            }else {
                result = "123456:"+statusCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            response.close();
        }
        return result;
    }

    @RequestMapping(value="/map", method=RequestMethod.POST)
    @ResponseBody
    public String requestList(@RequestParam Map<String, Object> param) {
        return "Request successful. Post param : Map - " + param;
    }


    /**
     * 获取用户登录时间
     * {"userId":root}
     * @param params
     * @return
     */
    @PostMapping("/getUserLoginTime")
    @Timed
    public String getUserLoginTime(String userId,@RequestBody String body) throws JsonParseException,IOException {

        String result = null;

        ObjectMapper mapper = new ObjectMapper();
        log.info("body="+body);
//        JsonNode actualObj = mapper.readTree(body);
//        log.info("actualObj="+actualObj.toString()+actualObj.get("userId"));
        try {
            JSONObject obj = new JSONObject();
            JSONObject obj2 = new JSONObject();
            obj2.put("startTime", "2017-12-05 13:56:24,130");
            obj2.put("endTime", "2017-12-05 13:56:24,430");
            obj2.put("ISCStartTime", "2017-12-05 13:56:24,230");
            obj2.put("ISCEndTime", "2017-12-05 13:56:24,332");
//            obj.put("userId", actualObj.get("userId"));
            obj.put("userId", userId);
            obj.put("time",obj2.toString());
            result = obj.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * JSON多参数版本
     * @param param
     * @param body
     * @return
     * @throws JsonParseException
     * @throws IOException
     */
    @PostMapping("/monV5/searchIndex")
    @Timed
    public String searchIndexV5(@RequestParam Map<String, Object> param,@RequestBody String body) throws JsonParseException, IOException, ParseException {
        String result = null ;
        List<MxpmsSearchEquipment> resultList = new ArrayList<MxpmsSearchEquipment>(); // 结果id集合
        JSONObject json = new JSONObject();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(body);
        String query_condition = actualObj.get("query_condition").toString();
        String search_date = actualObj.get("search_date").toString();
        log.info("search_date="+actualObj.get("search_date"));
        String subsearch_date = StrUtil.sub(search_date, 1, (search_date.length()-1));
        String[] arrSearchDate = subsearch_date.split("-");
        String index = "filebeat-"+arrSearchDate[0]+"."+arrSearchDate[1]+"."+arrSearchDate[2];
        String url = "http://127.0.0.1:9200/" + index + "/_search";
        StringEntity stringEntity = new StringEntity(query_condition, "UTF-8");
        log.info("index=========="+index+"query_condition=========="+query_condition);
        stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        HttpPost request = new HttpPost(url);
        request.setEntity(stringEntity);
        CloseableHttpResponse response = httpClient.execute(request);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if(HttpStatus.OK.value() == statusCode){
                HttpEntity entity = response.getEntity();
                if (entity != null){
                    result = EntityUtils.toString(entity, "utf-8");
                    log.info("result="+result);
                }
                EntityUtils.consume(entity);
            }else {
                if (HttpStatus.NOT_FOUND.value() == statusCode ){
                    HttpEntity entity = response.getEntity();
                    if (entity != null){
                        result = EntityUtils.toString(entity, "utf-8");
                        log.info("result="+result);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            response.close();
        }
        return result;
    }

    /**
     * 返回JSON数组
     * @param param
     * @param body
     * @return
     * @throws JsonParseException
     * @throws IOException
     * @throws ParseException
     */
    @PostMapping("/monV6/searchIndex")
    @Timed
    public String searchIndexV6(@RequestParam Map<String, Object> param,@RequestBody String body) throws JsonParseException, IOException, ParseException {
        String result = null ;
        List<MxpmsSearchEquipment> resultList = new ArrayList<MxpmsSearchEquipment>(); // 结果id集合
        JSONObject json = new JSONObject();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(body);
        String query_condition = actualObj.get("query_condition").toString();
        String search_date = actualObj.get("search_date").toString();
        log.info("search_date="+actualObj.get("search_date"));
        String subsearch_date = StrUtil.sub(search_date, 1, (search_date.length()-1));
        String[] arrSearchDate = subsearch_date.split("-");
        String index = "filebeat-"+arrSearchDate[0]+"."+arrSearchDate[1]+"."+arrSearchDate[2];
//        String url = "http://127.0.0.1:9200/" + index + "/_search";
        String url = "http://huicode.top:19200/" + index + "/_search";
        StringEntity stringEntity = new StringEntity(query_condition, "UTF-8");
        log.info("index=========="+index+"query_condition=========="+query_condition);
        stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        HttpPost request = new HttpPost(url);
        request.setEntity(stringEntity);
        CloseableHttpResponse response = httpClient.execute(request);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if(HttpStatus.OK.value() == statusCode){
                HttpEntity entity = response.getEntity();
                if (entity != null){
                    result = EntityUtils.toString(entity, "utf-8");
                    JSONObject a = new JSONObject(result);
                    log.info("大小="+result.length()+"result="+result+";obj="+a.getString("hits"));
                    log.info(";obj="+a.getString("hits"));
                    JSONObject hits = (JSONObject)(a.getJSONObject("hits"));
                    log.info("hits="+hits);
                    String total = (String) hits.getString("total");
                    log.info("total="+total);
                    String hitsString = (String) hits.getString("hits");
                    com.xiaoleilu.hutool.json.JSONArray array = JSONUtil.parseArray(hitsString);
                    Object[] obj = array.toArray();
                    com.xiaoleilu.hutool.json.JSONArray tableArray = JSONUtil.createArray();
                    com.xiaoleilu.hutool.json.JSONArray rowArray = JSONUtil.createArray();
                    log.info("array="+rowArray.toString());
                    for(int i=0;i<obj.length;i++){
                        JSONObject temp= new JSONObject(obj[i].toString());
                        log.info("obj="+temp.getString("_type")+"_source="+temp.getString("_source"));
                        JSONObject sourceJSONObject= new JSONObject(temp.getString("_source").toString());
                        String tempMessage = (String )sourceJSONObject.getString("message");
                        rowArray = JSONUtil.createArray();
                        String serverName = "服务器1";
                        String messageTime = tempMessage.substring(1,24);
                        String[] arrSplitMessage = tempMessage.split("SG-UAP");
                        String[] arrMethod = arrSplitMessage[1].split("-");         //调用的方法
                        String strMethod = (arrMethod[0].substring(7,arrMethod[0].length()))+"行";
                        int indexOfLog = tempMessage.indexOf('-',40);
                        int indexOfLog2 = indexOfLog + 2;
                        String text = tempMessage.substring((indexOfLog + 2),tempMessage.length());
                        int indexOfCostTime = text.indexOf("：");
                        String costTime = text.substring((indexOfCostTime+1),text.length());
                        rowArray.add(serverName);
                        rowArray.add(messageTime);
                        rowArray.add(strMethod);
                        rowArray.add(text);
                        if(costTime.indexOf("毫秒")>0){
                            costTime = costTime.substring(0,costTime.indexOf("毫秒"));
                        }
                        rowArray.add(costTime);
                        log.info("array="+rowArray.toString());
                        tableArray.add(rowArray);
                    }
                    log.info("tableArray="+tableArray.toString());
                    com.xiaoleilu.hutool.json.JSONObject tableJSON = JSONUtil.createObj();
                    com.xiaoleilu.hutool.json.JSONObject dataJSON = JSONUtil.createObj();
                    tableJSON.put("data", tableArray);
                    tableJSON.put("total", total);
                    tableJSON.put("pageNumber", 1);
                    tableJSON.put("pageSize", 100);
                    result = tableJSON.toString();
                    log.info("result="+result);
                }
                EntityUtils.consume(entity);
            }else {
                if (HttpStatus.NOT_FOUND.value() == statusCode ){
                    HttpEntity entity = response.getEntity();
                    if (entity != null){
                        result = EntityUtils.toString(entity, "utf-8");
                        log.info("result="+result);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            response.close();
        }
        return result;
    }


}
